export default {
    name: "exportxlsx",
    props: {
		bgsx: {
            type: Object,
            default: () => ({})
		},
		columns: {
            type: Array,
            default: () => []
        },
        viewcolum: {
            type: Array,
            default: () => []
        },
		ids: {
		    type: Array,
		    default: () => ([])
		},
        total: {
			type: Number,
			default: 0
		},
		filterForm: {
		    type: Object,
		    default: () => ({})
		}
    },
    setup(props, { emit }) {
        const rediskey = ref('');
        const percent = ref(0);
        const loading = ref(false);
        const dialogVisible = ref(false);
        const newids = ref(props.ids);
        const header = ref({
        	Accept: 'application/json',
        	Authorization: ''
        });
        
        watch(() => props.ids, (newIds, oldIds) => {
            newids.value = newIds;
        }, { immediate: true });
        
        // 计算进度条状态
        const progressStatus = computed(() => {
        	return percent.value >= 100 ? 'success' : '';
        });
        
        // 导出数据
        const dcsj = _.debounce(async (exportType) => {
        	if (!props.bgsx || Number(props.total) <= 0) {
        		ElMessage.warning('没有可导出的数据');
        		return;
        	}
            let selectedIds = [];
            let maxExport = 0;
            switch (exportType) {
                case 'all':
                case 'filter':
                    if (props.total <= 0) {
                        ElMessage.warning('没有可导出的数据');
                        return;
                    }
                    if (exportType == 'filter' && Object.keys(props.filterForm).length == 0) {
                        ElMessage.warning('请先点击高级筛选');
                        return;
                    }
                    selectedIds = [];
                    maxExport = props.total;
                    break;
                case 'selected':
                    selectedIds = newids.value;
                    if (selectedIds.length === 0) {
                        ElMessage.warning('请先选择要导出的行');
                        return;
                    }
                    maxExport = selectedIds.length;
                    break;
                default:
                    ElMessage.warning('无效的导出类型');
                    return;
            }
        	try {
                loading.value = true;
                dialogVisible.value = true;
                // 动态构建可见字段映射
                const visibleColumns = props.columns.filter(col => props.viewcolum.includes(col.prop));
                // 构建字段映射表
                const zd = visibleColumns.reduce((acc, col) => {
                    // 系统字段特殊处理
                    if (col.type === 'query_count') {
                        acc[col.prop] = '查询次数';
                    } else if (col.type === 'is_locked') {
                        acc[col.prop] = '锁定状态';
                    } else if (props.bgsx.isReservation && ['reservation_date','slot_start','slot_end','reservation_status'].includes(col.prop)) {
                        acc[col.prop] = col.label;
                    } else {
                        acc[col.prop] = col.label || props.bgsx.fields[col.prop]?.name;
                    }
                    return acc;
                }, {});
                // 添加固定系统字段（如果可见）
                const systemFields = {created_at: "创建时间",updated_at: "更新时间",cjz: "填报人"};
                Object.entries(systemFields).forEach(([key, label]) => {
                    if (props.viewcolum.includes(key)) {
                        zd[key] = label;
                    }
                });
                // 构建字段列表
                const zds = [
                    ...visibleColumns.map(c => c.prop),
                    ...Object.keys(systemFields).filter(k => props.viewcolum.includes(k))
                ];
                const res = await dcsjapi({
                    bm: props.bgsx.tablename,
                    ids: selectedIds,
                    zds: zds,
                    zd: zd,
                    lx: exportType,
                    max: maxExport,
                    filter: props.filterForm,
                });
                if (!res) {
                	throw new Error('Redis错误');
                }
                rediskey.value = res;
                startProgressPolling(maxExport);
        	} catch (error) {
        		ElMessage.error(error.message);
        		loading.value = false;
        		dialogVisible.value = false;
        	}
        }, 500);
        
        // 开始轮询进度
        const startProgressPolling = (max) => {
            const timer = setInterval(async () => {
                const res = await getjdapi({ rediskey: rediskey.value, max: max });
                switch (true) {
                    case res === -1:
                        percent.value = 0;
                        ElMessage.info("开始生成文件...");
                        break;
                    case res === 0:
                        percent.value = 95; // 伪进度，表示文件正在重命名
                        break;
                    case res === max + 1:
                        clearInterval(timer);
                        percent.value = 100;
                        await handleDownload();
                        loading.value = false;
                        break;
                    default:
                        let num = Number(((res / max) * 100).toFixed(1));
                        percent.value = Math.min(99, Math.max(0, num));
                }
            }, 1500);
        };
        
        // 处理下载
        const handleDownload = async () => {
            try {
                const fileUrl = `${window.APP_CONFIG.baseurl}uploads/excel/${rediskey.value}.xlsx`;
                // 步骤1：发送 HEAD 请求确认文件可访问
                const checkFile = async () => {
                    try {
                        await axios.head(fileUrl);
                        return true;
                    } catch {
                        return false;
                    }
                };
                // 步骤2：最多重试3次，每次间隔1秒
                let attempts = 0;
                while (attempts < 3) {
                    if (await checkFile()) break;
                    attempts++;
                    await new Promise(resolve => setTimeout(resolve, 1000));
                }
                if (attempts >= 3) {
                    throw new Error("文件下载准备超时");
                }
                // 步骤3：触发下载
                const link = document.createElement('a');
                link.href = fileUrl;
                link.download = `${rediskey.value}.xlsx`;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                ElMessage.success("文件下载开始");
            } catch (error) {
                ElMessage.error(`下载失败: ${error.message}`);
            }
        };

        return {
            rediskey,
            percent,
            loading,
            dialogVisible,
            progressStatus,
            dcsj,
            newids,
        }
        
    },
    
    template: `
	<div class="export-container">
        <el-dropdown @command="dcsj">
            <el-button type="primary" :disabled="loading" class="export-button">
                <template v-if="!loading">
                    <el-icon><document /></el-icon>导出数据<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </template>
                <template v-else>
                    <el-icon class="is-loading"><loading /></el-icon>导出中 ({{ percent }}%)
                </template>
            </el-button>
            <template #dropdown>
                <el-dropdown-menu>
                    <el-dropdown-item command="all">全部数据</el-dropdown-item>
                    <el-dropdown-item command="filter">筛选结果</el-dropdown-item>
                    <el-dropdown-item command="selected">选中行</el-dropdown-item>
                </el-dropdown-menu>
            </template>
        </el-dropdown>
		<el-dialog v-model="dialogVisible" title="文件生成进度" width="500px" :close-on-click-modal="false" :show-close="percent < 100">
			<div class="progress-container">
				<el-progress :percentage="percent" :status="progressStatus" :stroke-width="16" :text-inside="true" striped striped-flow>
					<template #default="{ v }">
						<span class="percentage-text" v-if="v > 0">
							{{ v.toFixed(0) }}%
							<el-icon v-if="v >= 100" color="#67C23A">
								<circle-check-filled />
							</el-icon>
						</span>
					</template>
				</el-progress>
				<div class="progress-tips">
					<template v-if="percent < 100">
						<el-icon class="loading-icon">
							<loading />
						</el-icon>
						<span>正在生成文件，请稍候...</span>
					</template>
					<template v-else>
						<el-icon class="success-icon"><circle-check-filled /></el-icon>
						<span>文件生成成功，即将开始下载</span>
					</template>
				</div>
			</div>
			<template #footer v-if="percent >= 100">
				<el-button type="success" @click="dialogVisible = false">关闭窗口</el-button>
			</template>
		</el-dialog>
	</div>
`
}